import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    ListView,
    Image,
    TouchableOpacity,
    Platform,
    Navigator,
    AsyncStorage
} from 'react-native';

var NavigatorBar = require('../Main/NXNavigationBar'); //NavigationBar
var Login = require('../Mine/NXLogin')
var screenWidth = Dimensions.get('window').width; //屏宽
var DynamicData = require('../Dynamic/DynamicData.json');
var DetailsView = require('../Mine/NXDetailsView');
import Dimensions from 'Dimensions'
var DetailsView = require('../Mine/NXDetailsView')
var dynamicdata = [];
var Dynamic = React.createClass({

    getInitialState(){
        // 初始化数据源
        return {
            dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            selectCellAction: null
        }
    },
    componentDidMount() {
        var token = '';
        try {
            AsyncStorage.getItem(
                'token',
                (error, result)=> {
                    if (error) {
                        //alert('取值失败:' + error);
                    } else {
                        //alert('取值成功:'+result);
                        this.token = result
                    }
                }
            )
        } catch (error) {
            alert('失败' + error);
        }
        let formData = new FormData();
        formData.append("start", '0');
        formData.append("limit", '5');
        formData.append("isNeedCategory", 'false');
        formData.append("lastRefreshTime", '2016-10-19 16-53-00');
        var fetchOptions = {
            method: 'POST',
            headers: {
                'token': this.token
            },
            body: formData,
        };

        let url = 'http://www.pintasty.cn/home/homedynamic';

        fetch(url, fetchOptions)
            .then((response) => response.json())
            .then((json) => {

                if (json.status == 200) {
                    console.log(json);
                    if (json.data.length == 0) {
                        alert('你还未发表评论')
                    } else {
                        if (json.data[0].obj == null) {
                            alert("还没有登录")
                            this.leftAction();
                        } else {
                            // 定义数组


                            for (var i = 0; i < json.data.length; i++) {
                                console.log(JSON.stringify(json.data[i].obj));
                                // 把组中内容放入dataBlob对象中
                                dynamicdata[i] = JSON.parse(json.data[i].obj);
                            }
                            this.setState({
                                dataSource: this.state.dataSource.cloneWithRows(dynamicdata)
                            });
                        }
                    }

                } else if (json.status == 301) {
                    alert('没有token')
                    this.leftAction();
                } else {
                    alert('访问服务器失败')
                }
            }).done();

    },

    render() {
        return (
            <View style={styles.container}>
                <NavigatorBar title='动态' widthWH={Platform.OS == 'ios' ? 15:15} leftBtnName='r_news_0'
                              rightBtnName='r_news_0'
                              leftpress={()=>this.leftAction()} rightPress={()=>this.rightAction()}/>


                <View style={styles.container}>
                    <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this._renderRow}
                    />
                </View>
            </View>
        );
    },

    _renderRow(rowData){
        return (
            <TouchableOpacity onPress={()=>this.passParasToDynamic(rowData)}>

                <View style={styles.all}>

                    <View style={styles.containers}>

                        <View style={[styles.viewstyles,styles.center]}>
                            <Image style={styles.img}
                                   source={{uri: rowData.comment_user_photo}}
                            />
                        </View>

                        <View style={styles.item}>
                            <View style={[styles.flex, styles.center]}>
                                <Text style={{fontSize:14,color:'red'}}> {rowData.comment_user_name} </Text>
                            </View >
                            < View style={[styles.flex, styles.center]}>
                                <Text style={{fontSize:12}}> {rowData.comment_user_sign} </Text>
                            </View>
                            < View style={[styles.flex, styles.center]}>
                                <Text style={{fontSize:10}}> {rowData.comment_create_time}
                                </Text>
                            </View>
                        </ View >

                        < View style={{height: 80}}>
                            <Text style={{fontSize:6}}> 他的评分：{rowData.comment_score}</Text >
                        </View>
                    </ View >

                    <View style={styles.commentscontent}>
                        <Text numberOfLines={2}> {rowData.comment_content} </Text>
                    </View>

                    <View >
                        <Image style={styles.testimg}
                               source={{uri: rowData.product_img} }/>
                    </View>
                    <View style={styles.container}>
                    </View>

                    <View
                        style={{width:screenWidth ,height: 1,backgroundColor:'rgba(200,200,200,1.0)',marginTop:8,marginBottom:16}}></View>
                </View>
            </TouchableOpacity>

        )
    },
    selectCellAction(rowData){
        this.props.navigator.push(
            {
                component: DetailsView,
                passProps: {
                    'product_id': rowData.product_id,
                    'uploadImgId': rowData.uploadImgId
                }
            }
        );
    },

    passParasToDynamic(rowData){
        console.log('222222222' + rowData.product_id);
        console.debug('debug--------------------' + rowData.product_id);
        //golbal.productId = rowData.product_id
        //golbal.uploadImgID = rowData.uploadImageId
        this.props.navigator.push(
            {
                component: DetailsView,
                passProps: {
                    'product_id': rowData.product_id,
                    'uploadImgId': rowData.uploadImgId
                }
            }
        );
    },

    leftAction() {
        this.props.navigator.push(
            {
                component: Login
            }
        );
    },

    rightAction() {
        try {
            AsyncStorage.getItem(
                'token',
                (error, result)=> {
                    if (error) {
                        alert('取值失败:' + error);
                    } else {
                        alert('取值成功:' + result);
                    }
                }
            )
        } catch (error) {
            alert('失败' + error);
        }
    },

    // 每一组中的数据
    renderSectionHeader(sectionData, sectionID){
        return (
            <View style={{height:20,borderBottomWidth:0.5,borderBottomColor:'#e8e8e8',marginTop:10}}>
                <Text style={{marginLeft:10,marginTop:3,fontSize:14}}>{sectionData}</Text>
            </View>
        );
    }
});

var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
    listView: {
        paddingTop: 20,
        backgroundColor: '#F5FCFF',
    },
    all: {
        flexDirection: 'column',
    },

    containers: {
        marginLeft: 14,
        marginRight: 14,
        flex: 1,
        flexDirection: 'row',
        height: 80,
    },

    item: {
        flex: 1,
        height: 80,
        width: 80,

    },

    center: {

        padding: 5
    },

    flex: {
        flex: 1,

    },

    commentscontent: {
        marginLeft: 14,
        marginRight: 14,
    },
    viewstyles: {
        flexDirection: 'row',
        justifyContent: 'center',

    },

    img: {
        width: 70,
        height: 70,
        borderRadius: 35
    },
    testimg: {
        marginTop: 10,
        marginLeft: 20,
        marginRight: 20,
        width: screenWidth - 40,
        height: screenWidth - 40,
        flexDirection: 'row',
        justifyContent: 'center',
    },

    interactive: {
        flexDirection: 'row',
        padding: 5,
    },
});


module.exports = Dynamic;